import 'package:go_router/go_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import '../../presentation/pages/auth/login_page.dart';
import '../../presentation/pages/auth/register_page.dart';
import '../../presentation/pages/auth/user_settings_page.dart';
import '../../presentation/pages/dashboard_page.dart';
import '../../presentation/pages/project/project_list_page.dart';
import '../../presentation/pages/project/project_detail_page.dart';
import '../../presentation/pages/todo/todo_list_page.dart';
import '../../presentation/pages/excel/excel_page.dart';
import '../../presentation/pages/admin/admin_dashboard_page.dart';
import '../../presentation/pages/spreadsheet/db_connection_page.dart';
import '../../presentation/pages/spreadsheet/table_selection_page.dart';
import '../../presentation/pages/spreadsheet/spreadsheet_page.dart';
import '../../presentation/pages/spreadsheet/spreadsheet_dashboard_page.dart';
import '../../presentation/pages/spreadsheet/connection_history_page.dart';
// 导入新的笔记和知识图谱页面
import '../../presentation/pages/note/note_list_page.dart';
import '../../presentation/pages/note/note_detail_page.dart';
import '../../presentation/pages/note/note_edit_page.dart';
import '../../presentation/pages/knowledge/knowledge_graph_page.dart';
// 导入需求管理页面
import '../../presentation/pages/requirement/requirement_list_page.dart';
import '../../presentation/pages/requirement/requirement_detail_page.dart';
import '../../presentation/pages/requirement/requirement_edit_page.dart';
import '../../presentation/providers/auth_provider.dart';
import '../../presentation/providers/dependencies.dart';

/// 应用路由配置
class AppRouter {
  static final GoRouter router = GoRouter(
    initialLocation: '/login',
    routes: [
      // 认证相关路由
      GoRoute(
        path: '/login',
        name: 'login',
        builder: (context, state) => const LoginPage(),
      ),

      GoRoute(
        path: '/register',
        name: 'register',
        builder: (context, state) => const RegisterPage(),
      ),

      GoRoute(
        path: '/settings',
        name: 'settings',
        builder: (context, state) => const UserSettingsPage(),
      ),

      // 主页路由（使用新的仪表板页面）
      GoRoute(
        path: '/dashboard',
        name: 'dashboard',
        builder: (context, state) => const DashboardPage(),
      ),

      // 项目相关路由
      GoRoute(
        path: '/projects',
        name: 'projects',
        builder: (context, state) => const ProjectListPage(),
        routes: [
          GoRoute(
            path: ':projectId', // 修复：移除开头的斜杠
            name: 'project-detail',
            builder: (context, state) {
              final projectId = int.parse(state.pathParameters['projectId']!);
              return ProjectDetailPage(projectId: projectId);
            },
          ),
        ],
      ),

      // 待办任务路由
      GoRoute(
        path: '/todos',
        name: 'todos',
        builder: (context, state) => const TodoListPage(),
      ),

      // 需求管理路由
      GoRoute(
        path: '/requirements',
        name: 'requirements',
        builder: (context, state) => const RequirementListPage(),
        routes: [
          GoRoute(
            path: 'create',
            name: 'requirement-create',
            builder: (context, state) => const RequirementEditPage(),
          ),
          GoRoute(
            path: ':requirementId',
            name: 'requirement-detail',
            builder: (context, state) {
              final requirementId =
                  int.parse(state.pathParameters['requirementId']!);
              return RequirementDetailPage(requirementId: requirementId);
            },
            routes: [
              GoRoute(
                path: 'edit',
                name: 'requirement-edit',
                builder: (context, state) {
                  final requirementId =
                      int.parse(state.pathParameters['requirementId']!);
                  return RequirementEditPage(requirementId: requirementId);
                },
              ),
            ],
          ),
        ],
      ),

      // Excel功能路由
      GoRoute(
        path: '/excel',
        name: 'excel',
        builder: (context, state) => const ExcelPage(),
      ),

      // 智能电子表格路由
      GoRoute(
        path: '/spreadsheet',
        name: 'spreadsheet-dashboard',
        builder: (context, state) => const SpreadsheetDashboardPage(),
      ),
      GoRoute(
        path: '/spreadsheet/connections',
        name: 'connection-history',
        builder: (context, state) => const ConnectionHistoryPage(),
      ),
      // 管理页面路由
      GoRoute(
        path: '/admin',
        name: 'admin',
        builder: (context, state) => const AdminDashboardPage(),
        routes: [
          // 笔记相关路由
          GoRoute(
            path: 'notes',
            name: 'note-list',
            builder: (context, state) => const NoteListPage(),
            routes: [
              GoRoute(
                path: 'create',
                name: 'note-create',
                builder: (context, state) => const NoteEditPage(),
              ),
              GoRoute(
                path: ':noteId',
                name: 'note-detail',
                builder: (context, state) {
                  final noteId = int.parse(state.pathParameters['noteId']!);
                  return NoteDetailPage(noteId: noteId);
                },
                routes: [
                  GoRoute(
                    path: 'edit',
                    name: 'note-edit',
                    builder: (context, state) {
                      final noteId = int.parse(state.pathParameters['noteId']!);
                      return NoteEditPage(noteId: noteId);
                    },
                  ),
                ],
              ),
            ],
          ),
          // 知识图谱路由
          GoRoute(
            path: 'knowledge-graph',
            name: 'knowledge-graph',
            builder: (context, state) => const KnowledgeGraphPage(),
          ),
        ],
      ),

      // 智能电子表格路由
      GoRoute(
        path: '/spreadsheet/connect',
        name: 'db-connect',
        builder: (context, state) => const DbConnectionPage(),
      ),
      GoRoute(
        path: '/spreadsheet/tables',
        name: 'table-selection',
        builder: (context, state) {
          final connectionConfig = state.extra as Map<String, dynamic>;
          return TableSelectionPage(connectionConfig: connectionConfig);
        },
      ),
      GoRoute(
        path: '/spreadsheet/:tableName',
        name: 'spreadsheet',
        builder: (context, state) {
          final tableName = state.pathParameters['tableName']!;
          final extra = state.extra as Map<String, dynamic>?;
          final connectionConfig =
              extra?['connectionConfig'] as Map<String, dynamic>?;
          final projectId = extra?['projectId'] as int? ?? 1;
          return SpreadsheetPage(
            tableName: tableName,
            projectId: projectId,
            connectionConfig: connectionConfig,
          );
        },
      ),
    ],

    // 路由重定向逻辑
    redirect: (context, state) async {
      // 获取认证状态
      final container = ProviderScope.containerOf(context);
      final authState = container.read(authStateProvider);

      final publicRoutes = ['/login', '/register'];

      // 如果是公开路由，直接通过
      if (publicRoutes.contains(state.fullPath)) {
        return null;
      }

      // 检查用户是否已认证
      if (authState is! AuthSuccess) {
        // 检查网络连接状态
        final connectivityResult = await Connectivity().checkConnectivity();
        final isOnline = !connectivityResult.contains(ConnectivityResult.none);

        if (!isOnline) {
          // 离线模式下，检查是否有本地存储的用户信息
          try {
            final authUseCases = container.read(authUseCasesProvider);
            final storedUserInfo = await authUseCases.getStoredUserInfo();

            if (storedUserInfo != null) {
              // 有本地用户信息，允许访问受保护的路由
              return null;
            }
          } catch (e) {
            // 静默处理错误
            print('检查本地用户信息时出错: $e');
          }
        }

        // 未认证用户重定向到登录页面
        return '/login';
      }

      return null;
    },

    // 错误页面
    errorBuilder: (context, state) => Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            SelectableText(
              '页面未找到',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            SelectableText(
              '路径: ${state.fullPath}',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => context.go('/dashboard'),
              child: const Text('返回首页'),
            ),
          ],
        ),
      ),
    ),
  );
}
